package com.xiwenlu.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;

public class DicTypePropertyWriter extends BeanPropertyWriter {
    private final BeanPropertyWriter baseWriter;
    private final String typeCode;
    private final DictProvider dictProvider;

    public DicTypePropertyWriter(BeanPropertyWriter baseWriter, String typeCode, DictProvider dictProvider) {
        super(baseWriter);
        this.baseWriter = baseWriter;
        this.typeCode = typeCode;
        this.dictProvider = dictProvider;
    }

    @Override
    public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
        // 1. 先正常序列化原字段
        baseWriter.serializeAsField(bean, gen, prov);

        // 2. 再额外写一个 Dic 字段
        Object value = baseWriter.get(bean); // 原字段值
//        String dicValue = getDictName(typeCode, value.toString());
        String dicValue = dictProvider.getDictName(typeCode, value == null ? null : value.toString());
        gen.writeStringField(baseWriter.getName() + "Dict", dicValue);
    }

}

